package com.xmut.bs.handaccount.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;

import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.adapter.ArticleAdapter;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bean.ArtContent;
import com.xmut.bs.handaccount.bean.ArtContentType;
import com.xmut.bs.handaccount.bmob.Article;
import com.xmut.bs.handaccount.bmob.Comment;
import com.xmut.bs.handaccount.bmob.Follow;
import com.xmut.bs.handaccount.bmob.Like;
import com.xmut.bs.handaccount.bmob.User;
import com.xmut.bs.handaccount.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.jzvd.JZVideoPlayer;

import static com.xmut.bs.handaccount.base.Constants.PARAM_ARTICLE_ID;

public class ArticleDetailActivity extends ToolbarBaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_note_content)
    RecyclerView mTvNoteContent;
    @BindView(R.id.comment_et)
    EditText mCommentEt;
    @BindView(R.id.like_cb)
    CheckBox mLikeCb;

    private ProgressDialog loadDialog;
    private Article article;
    private List<ArtContent> mList;
    private ArticleAdapter mAdapter;
    private ArtContent mComment;
    private User mUser;
    private Like mLike;
    private Follow mFollow;

    @Override
    protected String getSubTitle() {
        return "文章详情";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_article_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mList = new ArrayList<>();
        loadDialog = new ProgressDialog(this);
        loadDialog.setMessage("正在加载中...");
        loadDialog.setCanceledOnTouchOutside(false);
        mUser = BmobUser.getCurrentUser(User.class);
        loadDialog.show();
        mAdapter = new ArticleAdapter(mContext, mList);
        mAdapter.setOnFollowClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        mTvNoteContent.setLayoutManager(layoutManager);
        mTvNoteContent.setItemAnimator(new DefaultItemAnimator());
        mTvNoteContent.setAdapter(mAdapter);
        mTvNoteContent.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {
                JZVideoPlayer.onChildViewAttachedToWindow(view,R.id.video_player);
            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                JZVideoPlayer.onChildViewDetachedFromWindow(view);
            }
        });
        queryArticle();
    }

    private void queryArticle() {
        mList.add(new ArtContent(article));
        for (ArtContentType contentType : article.getContents()) {
            mList.add(new ArtContent(contentType));
        }
        mAdapter.notifyDataSetChanged();
        queryComment();
        queryLike();
        queryFollow();
    }

    private void queryFollow() {
        BmobQuery<Follow> query = new BmobQuery<>();
        query.addWhereEqualTo("followUser", mUser);
        query.addWhereEqualTo("followedUser", article.getUser());
        query.findObjects(new FindListener<Follow>() {
            @Override
            public void done(List<Follow> list, BmobException e) {
                if (e == null && list != null && list.size() > 0) {
                    mFollow = list.get(0);
                    mAdapter.setFollow(0, true);
                } else {
                    mAdapter.setFollow(0, false);
                }
            }
        });
    }

    private void queryLike() {
        BmobQuery<Like> query = new BmobQuery<>();
        query.addWhereEqualTo("user", mUser);
        query.addWhereEqualTo("article", article);
        query.findObjects(new FindListener<Like>() {
            @Override
            public void done(List<Like> list, BmobException e) {
                if (e == null && list != null && list.size() > 0) {
                    mLike = list.get(0);
                    mLikeCb.setChecked(true);
                }
            }
        });
    }

    private void queryComment() {
        BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("goods", null);
        query.addWhereEqualTo("article", article);
        query.order("-updatedAt");
        query.include("user");// 希望在查询帖子信息的同时也把发布人的信息查询出来
        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                loadDialog.dismiss();
                if (e == null) {
                    if (list.size() > 0) {
                        mComment = new ArtContent();
                        mList.add(mComment);
                        for (Comment comment : list) {
                            mList.add(new ArtContent(comment));
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    @Override
    protected void initParams(Intent intent) {
        article = (Article) intent.getSerializableExtra(PARAM_ARTICLE_ID);
    }

    @OnClick({R.id.send_btn, R.id.like_cb})
    public void onViewClicked(View view) {
        if (mUser == null) {
            showToast("请先登录");
            return;
        }
        switch (view.getId()) {
            case R.id.send_btn:
                sendBtnClick();
                break;
            case R.id.like_cb:
                likeBtnClick();
                break;
        }
    }

    private void likeBtnClick() {
        if (mLike == null) {
            final Like like = new Like(mUser, article);
            like.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        showToast("收藏成功");
                        mLike = like;
                        mLikeCb.setChecked(true);
                    } else {
                        mLikeCb.setChecked(false);
                        showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
            });
        } else {
            Like like = new Like(mUser, article);
            like.setObjectId(mLike.getObjectId());
            like.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        showToast("取消收藏");
                        mLike = null;
                        mLikeCb.setChecked(false);
                    } else {
                        showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                        mLikeCb.setChecked(true);
                    }
                }
            });
        }
    }

    private void sendBtnClick() {
        String trim = mCommentEt.getText().toString().trim();
        if (StringUtil.isNull(trim)) {
            showToast("评论内容不能为空");
            return;
        }
        final Comment comment = new Comment();
        comment.setArticle(article);
        comment.setComment(trim);
        comment.setUser(mUser);
        comment.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    showToast("评论成功");
                    if (mComment == null) {
                        mComment = new ArtContent();
                        mList.add(mComment);
                        mList.add(new ArtContent(comment));
                    } else {
                        int i = mList.indexOf(mComment);
                        mList.add(i + 1, new ArtContent(comment));
                    }
                    mCommentEt.setText("");
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    mAdapter.notifyDataSetChanged();
                } else {
                    showToast("评论失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onClick(View view) {
        if (mFollow == null) {
            final Follow follow = new Follow(mUser, article.getUser());
            follow.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        showToast("关注成功");
                        mFollow = follow;
                        mAdapter.setFollow(0, true);
                    } else {
                        showToast("关注失败");
                        mAdapter.setFollow(0, false);
                    }
                }
            });
        } else {
            Follow follow = new Follow(mUser, article.getUser());
            follow.setObjectId(mFollow.getObjectId());
            follow.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        showToast("取消关注成功");
                        mFollow = null;
                        mAdapter.setFollow(0, false);
                    } else {
                        showToast("取消关注失败");
                        mAdapter.setFollow(0, true);
                    }
                }
            });
        }
    }
}
